import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  message,
  Popconfirm,
  Card,
  Row,
  Col,
  Tag,
  Tooltip
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ExportOutlined,
  SearchOutlined,
  ReloadOutlined,
  SwapOutlined
} from '@ant-design/icons';
import { ContactApi, ContactVO, ContactPageParams } from '../../../api/crm/contact';

const { Option } = Select;

const ContactManagement: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [contacts, setContacts] = useState<ContactVO[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchParams, setSearchParams] = useState<ContactPageParams>({});
  const [modalVisible, setModalVisible] = useState(false);
  const [editingContact, setEditingContact] = useState<ContactVO | null>(null);
  const [form] = Form.useForm();

  // 性别选项
  const genderOptions = [
    { label: '男', value: 1 },
    { label: '女', value: 2 }
  ];

  // 获取联系人列表
  const fetchContacts = async () => {
    setLoading(true);
    try {
      const params = {
        pageNo: currentPage,
        pageSize,
        ...searchParams
      };
      const response = await ContactApi.getContactPage(params);
      setContacts(response.data.list || []);
      setTotal(response.data.total || 0);
    } catch (error) {
      message.error('获取联系人列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchContacts();
  }, [currentPage, pageSize, searchParams]);

  // 搜索处理
  const handleSearch = (values: any) => {
    setSearchParams(values);
    setCurrentPage(1);
  };

  // 重置搜索
  const handleReset = () => {
    setSearchParams({});
    setCurrentPage(1);
  };

  // 新增联系人
  const handleAdd = () => {
    setEditingContact(null);
    setModalVisible(true);
    form.resetFields();
  };

  // 编辑联系人
  const handleEdit = (record: ContactVO) => {
    setEditingContact(record);
    setModalVisible(true);
    form.setFieldsValue(record);
  };

  // 删除联系人
  const handleDelete = async (id: number) => {
    try {
      await ContactApi.deleteContact(id);
      message.success('删除成功');
      fetchContacts();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 转移联系人
  const handleTransfer = async (id: number, newOwnerUserId: number) => {
    try {
      await ContactApi.transferContact([id], newOwnerUserId);
      message.success('转移成功');
      fetchContacts();
    } catch (error) {
      message.error('转移失败');
    }
  };

  // 保存联系人
  const handleSave = async (values: ContactVO) => {
    try {
      if (editingContact) {
        await ContactApi.updateContact({ ...editingContact, ...values });
        message.success('更新成功');
      } else {
        await ContactApi.createContact(values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchContacts();
    } catch (error) {
      message.error('保存失败');
    }
  };

  // 导出联系人
  const handleExport = async () => {
    try {
      await ContactApi.exportContact(searchParams);
      message.success('导出成功');
    } catch (error) {
      message.error('导出失败');
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 120,
      ellipsis: true
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      key: 'mobile',
      width: 130,
      ellipsis: true
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 180,
      ellipsis: true
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      width: 80,
      render: (sex: number) => {
        const option = genderOptions.find(opt => opt.value === sex);
        return option ? <Tag color={sex === 1 ? 'blue' : 'pink'}>{option.label}</Tag> : '-';
      }
    },
    {
      title: '职位',
      dataIndex: 'post',
      key: 'post',
      width: 120,
      ellipsis: true
    },
    {
      title: '客户名称',
      dataIndex: 'customerName',
      key: 'customerName',
      width: 150,
      ellipsis: true
    },
    {
      title: '负责人',
      dataIndex: 'ownerUserName',
      key: 'ownerUserName',
      width: 100,
      ellipsis: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 120,
      render: (time: string) => time ? new Date(time).toLocaleDateString() : '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right' as const,
      render: (record: ContactVO) => (
        <Space>
          <Tooltip title="编辑">
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Tooltip title="转移">
            <Button
              type="link"
              size="small"
              icon={<SwapOutlined />}
              onClick={() => {
                Modal.confirm({
                  title: '转移联系人',
                  content: (
                    <Input
                      placeholder="请输入新负责人ID"
                      type="number"
                      onChange={(e) => {
                        const newOwnerUserId = Number(e.target.value);
                        if (newOwnerUserId) {
                          Modal.destroyAll();
                          handleTransfer(record.id!, newOwnerUserId);
                        }
                      }}
                    />
                  ),
                  okButtonProps: { style: { display: 'none' } },
                  cancelText: '取消'
                });
              }}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个联系人吗？"
            onConfirm={() => handleDelete(record.id!)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button
                type="link"
                size="small"
                danger
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <Row gutter={[16, 16]}>
          <Col span={24}>
            <Form
              layout="inline"
              onFinish={handleSearch}
              style={{ marginBottom: '16px' }}
            >
              <Form.Item name="name">
                <Input placeholder="联系人姓名" />
              </Form.Item>
              <Form.Item name="mobile">
                <Input placeholder="手机号" />
              </Form.Item>
              <Form.Item name="customerId">
                <Input placeholder="客户ID" />
              </Form.Item>
              <Form.Item name="sex">
                <Select placeholder="性别" style={{ width: 100 }} allowClear>
                  {genderOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item>
                <Space>
                  <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                    搜索
                  </Button>
                  <Button onClick={handleReset} icon={<ReloadOutlined />}>
                    重置
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </Col>
          <Col span={24}>
            <Space style={{ marginBottom: '16px' }}>
              <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                新增联系人
              </Button>
              <Button icon={<ExportOutlined />} onClick={handleExport}>
                导出
              </Button>
            </Space>
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={contacts}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1200 }}
          pagination={{
            current: currentPage,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, size) => {
              setCurrentPage(page);
              setPageSize(size || 10);
            }
          }}
        />
      </Card>

      {/* 新增/编辑联系人弹窗 */}
      <Modal
        title={editingContact ? '编辑联系人' : '新增联系人'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        width={800}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="姓名"
                rules={[{ required: true, message: '请输入姓名' }]}
              >
                <Input placeholder="请输入姓名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="mobile"
                label="手机号"
                rules={[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
                ]}
              >
                <Input placeholder="请输入手机号" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { type: 'email', message: '请输入正确的邮箱格式' }
                ]}
              >
                <Input placeholder="请输入邮箱" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="sex" label="性别">
                <Select placeholder="请选择性别">
                  {genderOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="post" label="职位">
                <Input placeholder="请输入职位" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="customerId" label="客户ID">
                <Input placeholder="请输入客户ID" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="qq" label="QQ">
                <Input placeholder="请输入QQ号" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="wechat" label="微信">
                <Input placeholder="请输入微信号" />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item name="address" label="地址">
                <Input placeholder="请输入地址" />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item name="remark" label="备注">
                <Input.TextArea rows={3} placeholder="请输入备注" />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};

export default ContactManagement;